<script setup>
import {
  Edit,
  Delete
} from '@element-plus/icons-vue'
import { getToken } from "@/utils/auth";
import { onMounted, ref, watch, reactive } from 'vue'
import { useConfirm } from '@/hooks/useConfirm'
import { ElMessage } from 'element-plus';
import { getCurrentInstance } from 'vue';
import {applyPage,applyAdd,applyUpdate,applyDelete,applyPass} from "@/api/stock/apply.js";
import {productAllService} from '@/api/stock/product'
import {batchstockListAll} from '@/api/stock/batchstock'

// 获取库存中的商品名称
const allProducts = ref([])
const allProduct = async() => {
  let r = await productAllService()
  console.log("data",r.data);
  allProducts.value = r.data
  // editModel.batchid =undefined
}
// 获取商品对应批次
const batches = ref([])
const allBatch = async()=>{
  editModel.value.batchid =undefined
  selectNum.value = ''
  console.log("222---",editModel.value.product);
  let r = await batchstockListAll({productsId:editModel.value.product})
  console.log("dddddd",r.data);
  console.log("dddddd",r.data.length);
  if(r.data.length == 0){
    alert('该商品无对应批次！')
  }
  console.log("batch",r.data);
  batches.value = r.data
  console.log(" batches.value", batches.value);

}
// 获取商品对应批次下的数量
const showNums = ref({})
const selectNum = ref()
const allNums = async()=>{
  let r = await batchstockListAll({
    productsId:editModel.value.product,
    batchId:editModel.value.batchid
  })
  showNums.value = r.data[0]
  console.log('111111',r);
  const a = showNums.value.productsNum
  const b = showNums.value.productsUnqualified
  const c = showNums.value.productsApply
  selectNum.value = a-b-c
}

const { proxy } = getCurrentInstance();  //获取当前实例
// 搜索栏数据
const validModel =  ref({
  productname: '',
  flag: ''
})

//分页条数据模型
const pageNum = ref(1)//当前页
watch(pageNum, () => { loadData() })
const total = ref(20)//总条数
const pageSize = ref(5)//每页条数

//当每页条数发生了变化，调用此函数
const onSizeChange = (size) => {
  pageSize.value = size;
  loadData();
}
//当前页码发生变化，调用此函数
const onCurrentChange = (num) => {
  pageNum.value = num;
  loadData();
}


// 列表数据模型
const tableData = ref([])
const param = ref({
  pageNumber: 1,
  pageSize: 10,
  userid:'',
  product:'',
  flag:''
})
// 
/** 获取列表数据  */
const loadData = async () => {
  let r = await applyPage(param.value)
 
    console.log('aaa', r.data.items)
    total.value = r.data.total;
    tableData.value = r.data.items;  
 
   
}

onMounted(() => {
  loadData()
  allProduct()
  // allBatch()
})

// 单选/多选判断
const single = ref(true);
const multiple = ref(true);


// const flags = ref([])
/** 选择条数  */
// function handleSelectionChange(selection) {
//   ids.value = selection.map(item => item.id);
//   flags.value = selection.map(item=>item.flag)
//   console.log("vvvvv",flags.value.includes(0));

//   single.value = selection.length != 1;
//   if(selection.length > 0){
//     if(flags.value.includes(0) || flags.value.includes(1)){
//       multiple.value = true
//     }else{
//     multiple.value = false
//   } 
// }else{
//   multiple.value = true
// }
// }

/** 行checkbox 选中事件 */
function handleSelectionChange(selection) {
    ids.value = selection.map(item => item.id);
    console.log("bgbgbg",ids.value);
}
// 批量删除
function check(row,index){
  console.log("ffff",row.flag);
  if(row.flag==0||row.flag==1){
    return false
  }return true;
}
/** 删除按钮操作 */
const ids = ref([]);
function handleDelete(row) {
  //点击行内的删除按钮时，row就有值
  const applyIds = row.id || ids.value;
  console.log("tgtgtg",applyIds);
  proxy.$modal.confirm('确认删除？').then(function () {
    return applyDelete(applyIds);
  }).then(() => {
    loadData();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => { });
};

// 新增/删除数据模型
const editModel = ref({
  product: '',
  batchid:'',
  amount: '',
  flag:1
})

//定义函数，清空数据模型的数据
const reset = () => {
  selectNum.value = ''
  editModel.value = {
    product: '',
    batchid:'',
    amount: '',
    flag:1,
  }
}

// 新增/编辑标题
const title = ref('')

// 新增/编辑标题
const dialogVisible = ref(false)

// 展示新增/编辑标题（标签中修改值不需要.value，函数中需要加.value）
const changeData = ref({})
const showDialog = (row) => {
  reset()
  dialogVisible.value = true;
  title.value = '编辑申请';
    console.log('row ',row)
  // 对ref对象的属性赋值
  editModel.value.product = row.product;
  editModel.value.batchid = row.batchid;
  editModel.value.batchname = row.batchname
  editModel.value.amount = row.amount;
  editModel.value.id = row.id
  editModel.value.flag = 1
  const numForChange = async() => {
    let r = await batchstockListAll({productsId:row.product,batchId:row.batchid})
    changeData.value = r.data[0]
    console.log("aaaaaaaa---",changeData.value);
    const a = changeData.value.productsNum
    const b = changeData.value.productsUnqualified
    const c = changeData.value.productsApply
    selectNum.value = a-b-c 
    
  }
  numForChange()
}
// 新增或编辑点取消时刷新数据
const onCancel = () => {
  dialogVisible.value = false
  loadData()
}


// 撤回
const returnApply = async (row) => {
  editModel.value.product = row.product;
  editModel.value.batchid = row.batchid;
  editModel.value.amount = row.amount;
  editModel.value.id = row.id
  editModel.value.abc = 1
  editModel.value.flag = 3
  let r = await applyUpdate(editModel.value)
  loadData()
}
// 表单验证
const rules = reactive({
  product: [
    { required: true, message: '请选择商品', trigger: 'blur' },
  ],
  batchid: [
    { required: true, message: '请选择批次', trigger: 'blur' },
  ],
  amount: [
    { required: true, message: '请输入数量', trigger: 'blur' },
  ]
})

/** 提交按钮 */
function submitForm() {
  proxy.$refs["addRef"].validate(valid => {
    if (valid) {
      // id != undefined标明有选中行，为新增，否则为修改
      if (editModel.value.id != undefined) {
        applyUpdate(editModel.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          dialogVisible.value = false;
          loadData();
        });
      } else {
        applyAdd(editModel.value).then(response => {
          if(selectNum.value>editModel.value.amount){
            proxy.$modal.msgSuccess("新增成功");
            dialogVisible.value = false;
          }else {
            proxy.$modal.msgSuccess("库存数量不足！");
          }
          loadData();
        });
      }
    }
  });
};

// 搜索
const showSearch = ref(true);

/** 重置按钮操作 */
function resetQuery() {
  // proxy.resetForm("queryRef");
  param.value.product = '',
  param.value.flag = ''
  loadData()
}


//导入
const upload = reactive({
  // 是否显示弹出层
  open: false,
  // 弹出层标题
  title: "",
  // 是否禁用上传
  isUploading: false,
  // 是否更新已经存在的用户数据
  updateSupport: 0,
  // 设置上传的请求头部
  headers: { Authorization: "Bearer " + getToken() },
  // 上传的地址
  url: "http://localhost:8080/applyTake/import"
})
/** 导入按钮操作 */
function handleImport() {
  upload.title = "领用列表导入"
  upload.open = true
};
/**文件上传中处理 */
const handleFileUploadProgress = (event, file, fileList) => {
  upload.isUploading = true;
};
/** 文件上传成功处理 */
const handleFileSuccess = (response, file, fileList) => {
  console.log('成功')
  upload.open = false;
  upload.isUploading = false;
  proxy.$refs["uploadRef"].handleRemove(file);
  proxy.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
  loadData();
};
/** 提交上传文件 */
function submitFileForm() {
  proxy.$refs["uploadRef"].submit();
};

// const isimport=ref(false)
// const importApply=(r)=>{
//   if(r.code==0){
//     isimport.value=false;
//     loadData();
//   }
// }

/** 导出按钮操作 */
function handleExport() {
  proxy.download("applyTake/export", {
    ...param.value
  }, `领用列表_${new Date().getTime()}.xlsx`);
}


</script>
<template>
  <el-card class="page-container">
    <!-- <template #header>
      <div class="header">
        <span>领用列表</span>
        <div>
          <el-button icon="Refresh" color="#626aef" @click="visibleDrawer = true">回收站</el-button>
        </div>
      </div>
    </template> -->

    <!-- 筛选 -->
    <el-form inline>
      <el-form :inline="true" :model="param" v-show="showSearch">
        <el-form-item label="商品名称" prop="product">           
            <el-select placeholder="请选择商品名称" v-model="param.product" style="width: 100%">
            <el-option
              v-for="item in allProducts"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="审批状态" prop="status">
                  <el-select                     
                     placeholder="审批状态"
                     clearable
                     style="width: 240px"
                     v-model="param.flag"
                  >
                  <el-option
                    v-for="item in [
                      { label: '通过', value: 0 },
                      { label: '未审批', value: 1 },
                      { label: '未通过', value: 2 },
                      { label: '已撤回',value: 3}
                    ]"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
                  </el-select>
               </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="loadData"> <span class="iconfont icon-sousuo"></span>搜索 </el-button>
          <el-button type="default" icon="Refresh" @click="resetQuery"> 重置 </el-button>
        </el-form-item>
      </el-form>
    </el-form>

    <!-- 按钮组 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus"
          @click="dialogVisible = true; title = '申请领用'; reset()">申请</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            icon="Delete"
            plain
            type="danger"
            :disabled="ids.length===0"
            @click="handleDelete"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="info" plain icon="Upload" @click="handleImport">导入</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport">导出</el-button>
      </el-col>

    </el-row>
    <!-- 按钮组 -->
    <!-- 表格 -->
    <el-table :data="tableData" :border="true" @selection-change="handleSelectionChange">
      <el-table-column type="selection" :selectable="check" align="center" fixed="left" ></el-table-column>
      <el-table-column label="序号" width="60" type="index" align="center">
        <!-- 序号重新计算 -->
        <template #default="scope">
          <span>{{ (pageNum - 1) * pageSize + scope.$index + 1 }}</span>
        </template>
      </el-table-column>
      <el-table-column label="商品名称" prop="productname" align="center"></el-table-column>
      <el-table-column label="商品批次" prop="batchname" align="center"></el-table-column>
      <el-table-column label="数量" prop="amount" align="center" width="60px"></el-table-column>
      <el-table-column label="审批状态" prop="flag" align="center">
        <template #default="scoped">
          <el-tag type="success" v-if="scoped.row.flag === 0">已通过</el-tag>
          <el-tag type="warning" v-else-if="scoped.row.flag === 1">未审批</el-tag>
          <el-tag type="danger" v-else-if="scoped.row.flag === 2">未通过</el-tag>
          <el-tag type="danger" v-else>已撤回</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="审批通过时间" prop="passTime" align="center"></el-table-column>
      <el-table-column label="操作" align="center" width="130" fixed="right">
        <template #default="{ row }">
          <el-button :icon="Edit" type="primary" v-if="row.flag==2||row.flag==3" link size="small" @click="showDialog(row)">
            <span class="iconfont icon-bianji"></span>修改
          </el-button>
          <el-button :icon="Edit" type="primary" v-if="row.flag==1" link size="small" @click="returnApply(row)">
            <span class="iconfont icon-bianji"></span>撤回
          </el-button>
          <el-button :icon="Delete" type="primary" v-if="row.flag==2||row.flag==3" link size="small" @click="handleDelete(row)">
            <span class="iconfont icon-shanchu"></span>删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 表格 -->
    <!-- 分页 -->
    <el-pagination 
      v-model:current-page="param.pageNumber" 
      v-model:page-size="param.pageSize" 
      :page-sizes="[10, 20, 30, 40]"
      layout="jumper, total, sizes, prev, pager, next" 
      background 
      :total="total" 
      @size-change="loadData"
      @current-change="loadData" 
      style="margin-top: 20px; justify-content: flex-end" />
    <!-- 分页 -->

    <!-- 添加/编辑菜单 -->
    <el-dialog v-model="dialogVisible" :title="title" width="50%">
      <el-form ref="addRef" :model="editModel" :rules="rules" label-width="100px" style="padding-right: 30px">
            <el-form-item label="商品名称" prop="product">           
            <el-select placeholder="请选择商品名称" v-model="editModel.product" @change="allBatch" style="width: 100%">
            <el-option
              v-for="item in allProducts"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="商品批次" prop="batchid">           
            <el-select v-model="editModel.batchid" placeholder="请选择批次" @change="allNums" style="width: 100%">
            <el-option
              v-for="item in batches"
              :key="item.batchId"
              :label="item.batchName"
              :value="item.batchId"
            />
          </el-select>
        </el-form-item>
            <el-row>
              <el-col :span="12">
                <el-form-item label="剩余数量" prop="selectNum">
                  <el-input disabled v-model="selectNum"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="领用数量" prop="amount">
                  <el-input v-model="editModel.amount"></el-input>
                </el-form-item>
              </el-col>
            </el-row>                  
            
         
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="onCancel">取消</el-button>
          <el-button type="primary" @click="submitForm()"> 提交
          </el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 导入按钮 -->
    <el-dialog :title="upload.title" v-model="upload.open" width="400px" append-to-body>
      <el-upload ref="uploadRef" :limit="1" accept=".xlsx, .xls" :headers="upload.headers" :action="upload.url"
        :disabled="upload.isUploading" :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess"
        :auto-upload="false" drag>
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <div class="el-upload__tip text-center">
            <span>仅允许导入xls、xlsx格式文件。</span>
          </div>
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFileForm">确 定</el-button>
          <el-button @click="upload.open = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- <el-dialog v-model="isimport" title="上传商品领用列表" width="500">
      <el-upload
          class="upload-demo"
          drag
          :on-success="importApply"
          action="http://127.0.0.1:8080/applyTake/import"
      >
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">
          请把上传的Excel拖拽到这里 <em>或者点击选择上传的文件</em>
        </div>
        <template #tip>
          <div class="el-upload__tip">
            Excel只支持xlxs格式的文件
          </div>
        </template>
      </el-upload>
    </el-dialog> -->

    <!-- 回收站抽屉 -->
    

  </el-card>
</template>
<style lang="scss" scoped>
.page-container {
  min-height: 100%;
  box-sizing: border-box;

  .header {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }

  .mb8 {
    margin-bottom: 8px;
  }
}
</style>